<template>
  <div class="page-classifyList">
    <filter-view @update-list="getTagList()" />
    <a-table
      :row-selection="{ selectedRowKeys: statusState.selectedRowKeys, checkStrictly: false, onChange: onSelectChange }"
      :expandRowByClick="false"
      row-key="tag_id"
      :columns="columns"
      :pagination="false"
      :data-source="state.tagList"
      :loading="state.loading"
      :scroll="{ x: 1500 }"
    >
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'tag_name'">
          <a-tooltip placement="top" color="#fff">
            <template #title>
              {{ record.tag_name }}
            </template>
            <div class="ellipsis-text">
              {{ record.tag_name || '-' }}
            </div>
          </a-tooltip>
        </template>
        <template v-else-if="column.key === 'tag_count'">
          <span>
            {{ formatNumber(record.tag_count) || '-' }}
          </span>
        </template>
        <template v-else-if="column.key === 'tag_module'">
          <span>
            {{ getModule(record.tag_module) || '-' }}
          </span>
        </template>
        <template v-else-if="column.key === 'created_at'">
          <span>
            {{ formatToDateTime(record.created_at * 1000) || '-' }}
          </span>
        </template>
        <template v-else-if="column.key === 'action'">
          <span>
            <a class="basicColor" @click="updateTag(record)">编辑</a>
            <a-divider type="vertical" />
            <a class="basicColor" @click="deleteTag(record)"> 删除 </a>
          </span>
        </template>
      </template>
    </a-table>
    <a-pagination
      @change="handlePaginationChange"
      show-size-changer
      :defaultPageSize="10"
      :pageSizeOptions="['10', '20', '50', '100']"
      :show-total="(total:number)=>`共${total}条`"
      :total="queryState.total"
    />
    <!-- 批量导入提示消息 -->
    <modal-dialog
      title="批量导入"
      v-model:visible="tipVisible"
      okText="确定"
      cancelText=" "
      :width="458"
      @confirm="tipConfirm"
      :showSingleBtn="true"
    >
      <span class="modal-text"> <check-circle-outlined style="" />导入成功！共30条数据 </span><br />
      <span class="modal-text"> <close-circle-outlined />导入失败！请检查文件表头是否与模板一致 </span>
    </modal-dialog>
    <!-- 删除对话框 -->
    <modal-dialog
      title="提示"
      v-model:visible="deleteVisible"
      okText="确定"
      cancelText="取消"
      :width="458"
      @confirm="deleteConfirm"
      @cancel="deleteCancel"
    >
      <span>确定要删除该标签吗</span>
    </modal-dialog>
    <!-- 添加/编辑对话框 -->
    <modal-dialog
      :title="statusState.isAdd ? '添加标签' : '编辑标签'"
      v-model:visible="statusState.formVisible"
      okText="确定"
      cancelText="取消"
      :width="511"
      :afterClose="afterCloseEdit"
      @confirm="formConfirm"
      @cancel="formCancel"
    >
      <a-form ref="formRef" :model="formState" :rules="formRules">
        <a-form-item label="标签名称" name="tag_name">
          <a-input
            v-model:value.trim="formState.tag_name"
            :maxlength="30"
            class="w-[359px]"
            placeholder="请输入标签名称"
          />
        </a-form-item>
        <a-form-item label="所属模块" name="tag_module">
          <a-select
            v-model:value="formState.tag_module"
            placeholder="所属模块"
            :disabled="statusState.isAdd ? false : true"
            class="select-m-r-24"
            :getPopupContainer="(triggerNode: any) => triggerNode.parentNode"
          >
            <a-select-option :value="item.value" v-for="item in MODULE_LIST" :key="item.value">{{
              item.label
            }}</a-select-option>
          </a-select>
        </a-form-item>
      </a-form>
    </modal-dialog>
    <!-- 批量导入对话框 -->
    <modal-dialog
      title="批量导入"
      class="batchBox"
      v-model:visible="statusState.batchVisible"
      okText="开始导入"
      cancelText="取消"
      :width="618"
      :afterClose="afterCloseFunc"
      @confirm="batchConfirm"
      @cancel="batchCancel"
    >
      <a-form>
        <a-form-item label="上传模板">
          <div>
            <div style="display: flex; align-items: center; height: 32px">
              <a-upload
                name="file"
                :fileList="fileList"
                :maxCount="1"
                :showUploadList="false"
                :multiple="false"
                :before-upload="beforeUpload"
                @change="handleChange"
              >
                <a-input-search v-model:value="templateFile" enter-button="上传文件" class="w-[334px]" />
              </a-upload>
              <a class="download-template" :href="`${baseUrl}v1/tag/template`" @click="handleTemplate">点击下载模板</a>
            </div>
            <p class="download-introduce">
              说明：可导入Excel文件，请先下载模板，填充数据再上传，模板表头请勿修改，文件大小不能超过200M
            </p>
            <!--
            <p class="download-info">文件读取到数据：<span>0条</span></p>
             -->
          </div>
        </a-form-item>
      </a-form>
    </modal-dialog>
  </div>
</template>
<script lang="ts" setup>
import { ref, onMounted, reactive, nextTick, computed, inject } from 'vue'
import { message } from 'ant-design-vue'
import { formatNumber, formatToDateTime } from '@/utils/format'
import FilterView from './components/FilterView.vue'
import { column, tagData, MODULE_LIST, MODULE_INFO } from './dataSource'
import { tagState, resetState, statusState } from './state'
import type { TagData } from '@/types/site/tag/tagList'
import ModalDialog from '@/components/components/modal/ModalView.vue'
import type { UploadProps } from 'ant-design-vue'
import apis from '@/apis'
import { storage } from '@/utils/storage'
const {
  site: { tag_add, tag_update, tag_list, tag_del, tag_template, tag_batch_add }
} = apis
const columns = ref(column)
const deleteVisible = ref(false)
const tipVisible = ref(false)
const baseUrl: any = inject('baseUrl')
console.log('baseUrl123: ', baseUrl)
const templateFile = ref('')
const deleteId = ref()
const siteId = storage.get('siteId')
console.log('siteId: ', siteId)
type Key = string
interface IState {
  loading: boolean
  tagList: TagData[]
  copyTableData: TagData[]
}
const state = reactive<IState>({
  loading: false,
  tagList: [],
  copyTableData: []
})
const formRef = ref()
interface IFormState {
  tag_name: string | undefined
  tag_module: number | undefined
  site_id?: string | undefined
  tag_id?: string | undefined
}
const queryState = reactive({
  offset: 0, // 默认当前页数
  limit: 10, // 默认当前页显示数据的大小
  total: 0 // 总数，必须先有
})
const fileList: any = ref([])

/**
 * 分页改变事件
 */
const handlePaginationChange = (size: number, limit: number) => {
  queryState.limit = limit
  queryState.offset = (size - 1) * limit
  getTagList()
}
//添加标签form数据
const formState = reactive<IFormState>({
  tag_name: '',
  tag_module: 1
})
const tagId = ref('')
const formRules = reactive({
  tag_name: [{ required: true, message: '请输入标签名称' }]
})
// 使用iframe框架下载文件--以excel为例，可修改type与fileName选择文件类型
// const downloadUrl = (res: any, name: string) => {
//   const blob = new Blob([res], { type: 'application/vnd.ms-excel' }) // 构造一个blob对象来处理数据
//   const fileName = name + '.xlsx' // 导出文件名
//   const elink = document.createElement('a') // 创建a标签
//   elink.download = fileName // a标签添加属性
//   elink.style.display = 'none'
//   elink.href = URL.createObjectURL(blob)
//   document.body.appendChild(elink)
//   elink.click() // 执行下载
//   URL.revokeObjectURL(elink.href) // 释放URL 对象
//   document.body.removeChild(elink) // 释放标签
// }
//下载模板
const handleTemplate = () => {
  tag_template().then((res: any) => {
    console.log('res: ', res)
    // const blob = new Blob([res.content])
    // const a = document.createElement('a')
    // a.download = res.fileName
    // a.href = URL.createObjectURL(blob)
    // a.click()
    // a.remove()
    // downloadUrl(res, '标签模板')
  })
}
//获取标签列表接口
const getTagList = () => {
  state.loading = true
  const params = {
    ...tagState,
    ...queryState
  }
  params.site_id = siteId
  if (!params.tag_id) params.tag_id = undefined
  // 更新列表接口
  tag_list(params)
    .then((res: any) => {
      state.tagList = res?.tags ?? []
      queryState.total = res?.total ?? 0
      state.loading = false
      //处理下一页，第一条删除问题
      if (queryState.offset >= (res?.tags ?? 0) && queryState.total != 0) {
        queryState.offset -= queryState.limit
        getTagList()
      }
    })
    .catch(() => {
      state.loading = false
    })
}
const onSelectChange = (rowKeys: Key[]) => {
  console.log('selectedRowKeys changed: ', rowKeys)
  statusState.selectedRowKeys = rowKeys
}
//行删除
const deleteTag = (item: TagData) => {
  deleteVisible.value = true
  deleteId.value = item.tag_id
  console.log(statusState.selectedRowKeys, '行删除id')
}
//编辑
const updateTag = (item: TagData) => {
  console.log('item: ', item)
  statusState.formVisible = true
  statusState.isAdd = false
  tagId.value = item.tag_id
  nextTick(() => {
    formRef.value.resetFields() //清除字段校验结果
    formState.tag_name = item.tag_name
    formState.tag_module = item.tag_module
  })
}
//提示
const tipConfirm = () => {
  tipVisible.value = false
}
/**
  删除标签对话框事件
 */
const deleteConfirm = (value: any) => {
  console.log('value: ', value)
  deleteVisible.value = value
  tag_del({ tag_id: [deleteId.value] }).then(() => {
    message.success('删除标签成功')
    getTagList()
  })
}
const deleteCancel = () => {
  deleteVisible.value = false
}
/**
  批量导入对话框事件
 */
const batchConfirm = (value: any) => {
  statusState.batchVisible = value
  handleUpload()
  // tipVisible.value = true
}
const batchCancel = () => {
  statusState.batchVisible = false
}
//重置表单
const afterCloseEdit = () => {
  formRef.value.resetFields()
}
/**
  添加编辑对话框事件
 */
const formConfirm = (value: any) => {
  console.log('value: ', value)
  formRef.value.validate().then(() => {
    //请求
    if (statusState.isAdd) {
      formState.site_id = storage.get('siteId')
      tag_add(formState).then(() => {
        message.success('添加标签成功')
        getTagList()
      })
    } else {
      formState.tag_id = tagId.value
      tag_update(formState).then(() => {
        message.success('编辑标签成功')
        getTagList()
      })
    }
    statusState.formVisible = value
  })
}
const formCancel = () => {
  statusState.formVisible = false
}
// 上传文件
const handleChange = (info: any) => {
  console.log('上传文件', info)
  console.log('info.fileList[0].originFileObj: ', info.fileList[0].originFileObj)
  fileList.value = [info.fileList[0].originFileObj]
}

// 上传按钮
const beforeUpload: UploadProps['beforeUpload'] = (file: any) => {
  console.log('file11111111: ', file)
  // templateFile.value = file.name
  // fileList.value = [file]
  // return false

  templateFile.value = file.name
  var fileType = file.name.split('.')
  if (
    // fileType[fileType.length - 1] === 'doc' ||
    // fileType[fileType.length - 1] === 'docx' ||
    // fileType[fileType.length - 1] === 'ppt' ||
    // fileType[fileType.length - 1] === 'pdf' ||
    // fileType[fileType.length - 1] === 'txt' ||
    fileType[fileType.length - 1] === 'xlsx'
    // fileType[fileType.length - 1] === 'xls'
  ) {
    fileList.value = [file]
    console.log('fileList.value: ', fileList.value)
    return new Promise((reject) => false)
  } else {
    // message.info('上传文件类型不支持（仅支持文本文档、PPT、PDF、表格文档）')
    message.warning('上传文件类型不支持（仅支持xlsx格式）')
    return new Promise((reject) => false)
  }
}
//开始上传
const handleUpload = () => {
  console.log('fileList.value123: ', fileList.value)
  console.log('fileList.value[0]: ', fileList.value[0])
  if (fileList.value.length === 0) return message.warning('请上传文件')
  const formData = new FormData()
  formData.append('file', fileList.value[0])
  formData.append('site_id', siteId)
  tag_batch_add(formData).then((res: any) => {
    message.success('批量导入成功')
    getTagList()
  })
}
const afterCloseFunc = () => {
  fileList.value = []
  templateFile.value = ''
}
const getModule = computed(() => (type: number) => {
  return MODULE_INFO[type]
})
onMounted(() => {
  getTagList()
})
</script>
<style lang="less" scoped>
@basicColor: #0083ff;

:deep(.ant-upload-list) {
  display: none;
}

.modal-text {
  font-size: 16px;
  color: #595959;
}

:deep(.ant-form-item-label) {
  width: 80px;
  text-align: right;
}

:deep(.ant-form-item-label > label::after) {
  content: '';
}

.batchBox {
  .download-template {
    margin-left: 16px;
  }

  .download-introduce {
    font-size: 12px;
    color: #bfbfbf;
    margin-top: 8px;
  }

  .download-info {
    font-size: 14px;
    color: #595959;

    span {
      color: #262626;
    }
  }
}

.page-classifyList {
  padding-top: 6px;
  box-sizing: border-box;

  :deep(.ant-table-thead > tr > th) {
    color: #262626;
    font-weight: 500;
  }

  :deep(
      .ant-table-thead
        > tr
        > th:not(:last-child):not(.ant-table-selection-column):not(.ant-table-row-expand-icon-cell):not(
          [colspan]
        )::before
    ) {
    width: 0;
  }

  :deep(.ant-table-cell .ant-table-cell-with-append) {
    display: flex;
    align-items: center;
  }

  :deep(.ellipsis-text) {
    max-width: 170px !important;
    white-space: nowrap;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
    cursor: pointer;
  }

  .basicColor {
    color: @basicColor;
  }
}
</style>
